package net.yambal.air.mobile.manager
{
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.SharedObject;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	import jp.cre8system.framework.airrecord.db.ARDatabase;
	
	import mx.events.FlexEvent;
	
	import spark.components.View;
	import spark.components.ViewNavigatorApplication;

	[Event(name="init", type="net.yambal.air.mobile.manager.AppManagerEvent")]
	[Event(name="sized", type="net.yambal.air.mobile.manager.AppManagerEvent")]
	public class AppManager extends EventDispatcher
	{
		private static var _instance:AppManager;
		private var _shared_object:SharedObject = null;
		
		private var _vna:ViewNavigatorApplication = null;

		
		private var _init:Boolean = false;
		private var _currentView:IManagedView = null;
		private var _backView:Class = null;
		
		public var width:Number = 0;
		public var height:Number = 0;
		
		private var _appName:String = null;
		private var _appID:String = null;
		private var _filename:String = null;
		
		//private var _app_dir:File = null;
		private var _sd_dir:File = null;
		//private var _user_app_dir:File = null;
		private var _user_app_img_dir:File = null;
		private var _app_data_dir:File = null;
		
		public function AppManager(){
			var appXml:XML = NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace = appXml.namespace();
			_appName = appXml.ns::filename[0];
			_appID = appXml.ns::id[0];
			_filename = appXml.ns::filename[0];

			// SDのパス
			_sd_dir = File.userDirectory;
			
			_app_data_dir = File.applicationStorageDirectory;

			// デジタルカメラのDir
			var _user_dcim_dir:File = new File(_sd_dir.nativePath + "/DCIM");
			
			if(_user_dcim_dir.exists){
				_user_app_img_dir = _user_dcim_dir.resolvePath(_filename);
				_user_app_img_dir.createDirectory();
				
			}else{
				//_user_app_dir = _user_dir.resolvePath(_filename);
				//_user_app_dir.createDirectory();
				_user_dcim_dir = null;
				_user_app_img_dir = _sd_dir.resolvePath(_filename);
				_user_app_img_dir.createDirectory();
			}
			
			// SharedObject
			_shared_object = SharedObject.getLocal("bkmt");
			if(typeof _shared_object.data.init == "undefined"){
				_shared_object.data.init = true;
				
				_shared_object.data.image_count = 0;
				_shared_object.flush();
			}
			

			
			trace("UserDir(sd) : " + _sd_dir.nativePath);
			trace("UserAppImgDir: " + _user_app_img_dir.nativePath);
		}
		
		public static function getInstance():AppManager {
			if(_instance == null){
				_instance = new AppManager();
			}
			return _instance;
		}
		
		/**
		 *
		 **/
		public function setViewNavigatorApplication(vna:ViewNavigatorApplication):void{
			_vna = vna;
			_vna.addEventListener(FlexEvent.CREATION_COMPLETE, onAppCreateComplate);
		}
		
		private function onAppCreateComplate(e:FlexEvent):void{
			 if(_vna != null){
				 _vna.removeEventListener(FlexEvent.CREATION_COMPLETE, onAppCreateComplate);
				 width = _vna.width;
				 height = _vna.height;
			 }
			 
			 NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			 
			 _init = true;
			 dispatchEvent(new AppManagerEvent(AppManagerEvent.INIT));
			 dispatchEvent(new AppManagerEvent(AppManagerEvent.SIZED, width, height));
			 
			 if(_currentView != null){
				 _currentView.clearView();
				 _currentView.onAppRagistrated(width, height);
			 }
		}
		
		public function getWidthHeight():void{
			if(_init){
				dispatchEvent(new AppManagerEvent(AppManagerEvent.SIZED, width, height));
			}
		}
		
		public function onViewActiveThenRegistrationView(view:IManagedView, backView:Class = null):void{
			_currentView = view;
			_backView = backView
			
			if(_init){
				_currentView.clearView();
				_currentView.onAppRagistrated(width, height);
			}
		}
		
		/**
		 * ビューを変更する
		 * 一気にやるとバグる
		 **/
		public function viewChangeTo(nextView:Class, data:Object):void{
			_currentView.call_later(viewChangeTo2, [nextView, data]);
		}
		
		private function viewChangeTo2(nextView:Class, data:Object):void{
			_currentView.clearView();
			_currentView.call_later(viewChangeTo3, [nextView, data]);
		}
		
		private function viewChangeTo3(nextView:Class, data:Object):void{
			_currentView.view_navigator.replaceView(nextView, data);
			
			_currentView = null;
			_backView = null;
		}
		
		/**
		 * 
		 **/
		public function onKeyDown(event:KeyboardEvent):void 
		{ 
			trace("onKeyDown:" + event.keyCode);
			
			switch (event.keyCode)  {
				case Keyboard.MENU:
					trace("メニューキーが押された"); 
					break;
				case Keyboard.SEARCH:
					trace("サーチキーが押された");
					break;
				case Keyboard.BACK:
					trace(this + ":バックキーが押された");
					event.preventDefault();
					onClickBack();
					break;
			}
		}
		
		private function onClickBack():void{
			if(_backView == null){
				_currentView.clearView();
				appExit();
			}else{
				_currentView.clearView();
				viewChangeTo(_backView, null);
			}
		}
		
		private function appExit():void{
			_currentView.beforExitApp();
			NativeApplication.nativeApplication.exit();
		}
		
		
		public function save_image(byte_array:ByteArray, file_name:String):String{
			var name_exe:Array = file_name.split(".");
			var n:Number = 0;

			var save_file:File = _user_app_img_dir.resolvePath(file_name);
			while(save_file.exists){
				n++;
				file_name = name_exe[0] + "-" + n + "." + name_exe[1];
				save_file = _user_app_img_dir.resolvePath(file_name);
			}
			
			trace("save:" + save_file.nativePath);
			
			var stream:FileStream = new FileStream();
			stream.openAsync(save_file, FileMode.WRITE);
			stream.writeBytes(byte_array);
			stream.close();
			
			trace("saved:" + save_file.nativePath);
			
			return save_file.nativePath;
		}
		
		public function simpleCounter():Number{
			trace("simpleCounter");
			
			var ret:Number = _shared_object.data.image_count + 1;
			_shared_object.data.image_count = ret;
			_shared_object.flush();
			
			return ret;
		}
	}
}